// weak security

// thank you http://rumkin.com
// thank you http://www.webtoolkit.info/javascript-base64.html

var nonce64 = {

'encode': function( msg, hash ) {
	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var output = '';
	var out_arr = [];
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

	msg = this.utf8_encode( msg );

	while( i < msg.length ) {
		chr1 = msg.charCodeAt(i++);
		chr2 = msg.charCodeAt(i++);
		chr3 = msg.charCodeAt(i++);

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3)  << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if( isNaN(chr2) )	enc3 = enc4 = 64;
		else if( isNaN(chr3) )	enc4 = 64;

		output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
		out_arr.push(enc1);
		out_arr.push(enc2);
		out_arr.push(enc3);
		out_arr.push(enc4);
	}

	// scramble as per hash
	if( hash == undefined ) hash = state.session.rand + state.session.hash;
	var seed = hash.toString(8);
	console.log( "msg="+msg+" hash="+hash+", seed="+seed );
	var scrambled = '';
	for( var ct=0; ct<out_arr.length; ct++ ) {
		var offset = parseInt( seed.substr( ct%(seed.length-1), 2 ), 8 );
		var val = (out_arr[ct] + offset) % 64;
		//-console.log( 'sub='+seed.substr( ct%(seed.length-1), 2 )+', offset='+offset+', val='+val );
		scrambled += keyStr.charAt(val);
	}

	//-console.log( 'scrambled: '+scrambled );
	return scrambled;
},

'utf8_encode': function( string ) {

	string = string.replace(/\r\n/g,"\n");
	var utftext = "";

	for (var n = 0; n < string.length; n++) {
		var c = string.charCodeAt(n);
		if (c < 128) {
			utftext += String.fromCharCode(c);
		}
		else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}
		else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}
	}

	return utftext;
}

};
